/*
 * @Author: wuqingchun
 * @Date: 2024-09-29 17:00:17
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-10-03 14:42:41
 */
#include "chat_net.h"
#include "chat_errno.h"

CChatNet::CChatNet(const char* pcServerHost, uint16_t usPort):
    m_objNetAddr({pcServerHost, usPort}),
    m_objTcpClient(m_objThread.startLoop(), m_objNetAddr, "chat_client")
{
    m_objTcpClient.setConnectionCallback(std::bind(&CChatNet::__OnConnect, this, _1));

    m_objTcpClient.enableRetry();
    m_objTcpClient.connect();
}

CChatNet::~CChatNet()
{

}

void CChatNet::setMessageCallback(const MessageCallback& refMsgCB)
{
    m_objTcpClient.setMessageCallback(refMsgCB);
}

int32_t CChatNet::Send(CHAT_MSG_HEAD_S& refMsg)
{
    if (m_pConn != nullptr)
    {
        Buffer objBuffer;

        size_t ulBufLen = sizeof(CHAT_MSG_HEAD_S) + refMsg.uiMsgLen;
        refMsg.uiMsgLen = htonl(refMsg.uiMsgLen);
        refMsg.usVersion = htons(refMsg.usVersion);
        refMsg.usType = htons(refMsg.usType);
        objBuffer.append(&refMsg, ulBufLen);
        m_pConn->send(&objBuffer);

        return CHAT_ERR_OK;
    }

    return CHAT_ERR_NOT_CONNECT;
}

void CChatNet::__OnConnect(const TcpConnectionPtr& refConnPtr)
{
    if (refConnPtr->connected())
    {
        printf("Connection %p opened\n", refConnPtr.get());
        m_pConn = refConnPtr;
    }
    else
    {
        printf("Connection %p closed\n", refConnPtr.get());
        m_pConn = nullptr;
    }
}


